package com.ys.peony.ui.fragment;

import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.base.BaseFragment;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.domain.ReportModel;
import com.ys.peony.ui.view.MyChartView;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.ToastUtils;
import com.ys.peony.utils.YsUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;

/**
 * describe:数据Fragment
 * author:yukang
 * date:2017/8/27 23:02
 */
public class ReportFragment extends BaseFragment implements OnClickCommonListener {


    private final static String SHI_WAN = "100000";
    private final static String WAN = "10000";
    @BindView(R.id.nestedscroll)
    NestedScrollView nestedscroll;
    @BindView(R.id.columnChart)
    MyChartView mChart;

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.price)
    TextView price;

    private CommonRecyclerViewAdapter mAdapter;
    private List<ReportModel.ShopLoanInfoListBean> mList;
    private LinearLayoutManager mLayoutManager;

    private boolean isReverse = false;

    @Override
    public int getLayoutRes() {
        return R.layout.report_fragment;
    }

    @Override
    public void initView() {
        mRecyclerView.setFocusable(false);
        initMenu();
        initData();
        initChart();
        setAdapter();
        updateView();
        getReportData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    private void initChart() {

        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);

        mChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);

        //x轴
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        //y轴
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(5, false);
        leftAxis.setDrawGridLines(false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        mChart.getAxisRight().setEnabled(false);
    }


    /**
     * 描述：初始化menu
     */
    private void initMenu() {
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
        ((BaseActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rotate(view);
                getReportData();
            }
        });
    }

    private void initData() {
        mList = new ArrayList<>();
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mLayoutManager.setAutoMeasureEnabled(true);
        mAdapter = new CommonRecyclerViewAdapter<ReportModel.ShopLoanInfoListBean>(getContext(), mList, R.layout.view_reportdata_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
                super.onBindViewHolder(holder, position);
                if (!isFooterView(position)) {
                    ReportModel.ShopLoanInfoListBean shopLoanInfoListBean = mList.get(position);
                    if (shopLoanInfoListBean == null) {
                        return;
                    }
                    String area = shopLoanInfoListBean.getShop_org_name() + "放款金额（万元）";
                    String price_all = YsUtil.div(shopLoanInfoListBean.getLoan_amount(), new BigDecimal(WAN), 4);
                    String price_today = YsUtil.div(shopLoanInfoListBean.getDayLoanInfoList().get(0).getLoan_amount(), new BigDecimal(WAN), 4);
                    String price_yesterday = YsUtil.div(shopLoanInfoListBean.getDayLoanInfoList().get(1).getLoan_amount(), new BigDecimal(WAN), 4);

                    ((CommonRecyclerViewHolder) holder).setText(R.id.area, area)
                            .setText(R.id.price_all, price_all)
                            .setText(R.id.price_yesterday, price_yesterday)
                            .setText(R.id.price_today, price_today);
                }
            }
        };
        mAdapter.setOnClickListener(this);
        mAdapter.isHasFooter(true);
    }

    private void setAdapter() {
        mRecyclerView.addItemDecoration(new Divider(getContext()));
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * describe:获取report数据
     * author:yukang
     */
    private void getReportData() {
        if (!NetUtils.isNetworkConnected(getBaseActivity())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        httpManagerUtils.get(HttpURL.shopLoanInfo, params, new BaseRespCallBack(getBaseActivity()) {
            public void onRespSuccess(String respStr) {
                ReportModel reportModel = JSONUtil.parseObject(respStr, ReportModel.class);
                mList.clear();
                if (reportModel != null && reportModel.getShopLoanInfoList() != null) {
                    mList.addAll(reportModel.getShopLoanInfoList());
                    updateView();
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    private void updateView() {
        updateTopView();
        updateCenterView();
        updateBottomView();
    }

    private void updateTopView() {
        List<BigDecimal> list = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            list.add(mList.get(i).getLoan_amount());
        }
        if (mList.size() < 1) {
            return;
        }
        BigDecimal bigDecimal = YsUtil.addAll(list);
        String all = YsUtil.div(bigDecimal, new BigDecimal(WAN), 4);
        price.setText(all);
    }

    private void updateCenterView() {
        setChartData();
    }


    private void setChartData() {
        if (mList.size() < 1) {
            return;
        }
        ArrayList<BarEntry> yVals1 = new ArrayList<>();
        String[] values = new String[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            String loan_amount = YsUtil.div(mList.get(i).getLoan_amount(), new BigDecimal(SHI_WAN), 2);
            yVals1.add(new BarEntry(i, Float.valueOf(loan_amount)));
            values[i] = mList.get(i).getShop_org_name().substring(0, 2);
        }
        BarDataSet set1;
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "近三个月放款额");
            set1.setDrawIcons(false);
            set1.setColor(Color.parseColor("#fd6d5d"));
            set1.setHighLightAlpha(20);
            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);
            mChart.setData(data);

        }
        XAxis xAxis = mChart.getXAxis();
        xAxis.setValueFormatter(new MyXAxisValueFormatter(values));
        animateY();
    }

    private void updateBottomView() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClickListener(View view, int position) {

    }

    /**
     * 点击FloatingActionButton时旋转
     */
    public void rotate(View view) {
        int rotate = isReverse ? 180 : -180;
        ObjectAnimator.ofFloat(view, "rotation", 0.0f, rotate)
                .setDuration(600).start();
        isReverse = !isReverse;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            animateY();
        }
    }

    static class MyXAxisValueFormatter<T> implements IAxisValueFormatter {
        private String[] mValues;

        public MyXAxisValueFormatter(String[] values) {
            this.mValues = values;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return mValues[(int) value];
        }
    }

    private void animateY() {
        mChart.animateY(2000);
    }
}
